var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var app = getApp()
const {
  wxml,
  style
 } = require('./utils.js')
// pages/ucenter/help/help.js
Page({
  data:{
    userInfo: {},
    helpList: []
  },
  //获取海报数据
  getServerData(){
    var that =this
    wx.showLoading({
      title:'海报生成中...'
    })
    let params={
      "envVersion":"trial" //正式版为 "release"，体验版为 "trial"，开发版为 "develop"
    }
    util.request(api.getQRCode, params,'post','application/json').then(function (res) {
      if (res.imgUrl) {
        that.setData({ 
          qrcode_img: res.imgUrl
        })
        const {name,share_img,qrcode_img} = {
          name:app.globalData.userInfo.referralCode,
          share_img:'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
          qrcode_img:res.imgUrl
        }
        that.widget = that.selectComponent('.widget');
        const _wxml = wxml(name,share_img,qrcode_img)
        setTimeout(()=>{      
          const p1 = that.widget.renderToCanvas({
              wxml: _wxml,
              style
          });
          p1.then((res)=>{
            wx.hideLoading()
          })
        },500)
      }
    });     
    
  },
  //生成海报 
  async preservation() {
    const p2 = this.widget.canvasToTempFilePath()
    p2.then(res => {
      // this.setData({
      //     src: res.tempFilePath,
      //     width: that.container.layoutBox.width,
      //     height: that.container.layoutBox.height,
      // },function(){
      //     wx.hideLoading();
      // })
      wx.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success(res){
          wx.showToast({
            title: '海报已保存，快去朋友圈分享吧',
          })
        },
        fail(res){
          wx.showToast({
            icon:'error',
            title: '保存图片失败',
          })
        }
      })
    }).catch(fail => {
      wx.hideLoading();
      wx.showToast({
          icon: 'error',
          title: '请稍后再试',
      })
  })
  },
  RecommendList() {
    let that = this;
    util.request(api.GetUserInfo, {},'get').then(function (res) {
      if (res.errno === 0) {
        that.setData({
          helpList: res.data
        })
      }
    });
  },
  onLoad:function(options){
    // 页面初始化 options为页面跳转所带来的参数
    this.RecommendList()
    
  },
  onReady:function(){
    // 页面渲染完成
  },
  onShow:function(){
    let userInfo = wx.getStorageSync('userInfo');
    let token = wx.getStorageSync('token');

    // 页面显示
    if (userInfo && token) {
      app.globalData.userInfo = userInfo;
      app.globalData.token = token;
    }

    this.setData({
      userInfo: app.globalData.userInfo,
    },()=>{
      this.getServerData()
    });
    // 页面显示
  },
  onHide:function(){
    // 页面隐藏
  },
  onUnload:function(){
    // 页面关闭
  }
})